﻿using SelfMadeMillionaire.Core.Entities;
using SelfMadeMillionaire.Core.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SelfMadeMillionaire.Core.Specifications.Publications
{
	public class RecentIssuesSpecification : ISearchSpecification<Newsletter>
	{
		private int _count;
		private ProductType _productType;
		private SubscriptionType _minAccessLevel;
        private int? _issueType;
        private int? _excludeId;
        private string _symbol;

		public RecentIssuesSpecification(int showCount, ProductType productType, SubscriptionType minAccessLevel)
		{
			_count = showCount;
			_productType = productType;
			_minAccessLevel = minAccessLevel;
		}

        public RecentIssuesSpecification(int showCount, ProductType productType, SubscriptionType minAccessLevel, int? issueType, int? excludeId, string symbol)
        {
            _count = showCount;
            _productType = productType;
            _minAccessLevel = minAccessLevel;
            _issueType = issueType;
            _excludeId = excludeId;
            _symbol = symbol;
        }

		public IEnumerable<Newsletter> SatisfiedBy(IQueryable<Newsletter> entities)
		{
            IEnumerable<Newsletter> result = entities.Where(p => p.Status == (byte)StatusType.Active 
										&& p.IssueType.Title != "Portfolio Performance"
										
                                        && (
                                            (p.Letter == (byte)_productType) ||
                                            (p.Products.Any(x => x.ProductType == (byte)_productType))
                                        )


										&& p.MinAccessLevel <= (byte)_minAccessLevel
                                        && p.IssueType.ID == (_issueType.HasValue ? _issueType.Value : p.IssueType.ID)
                                        && p.ID != (_excludeId.HasValue ? _excludeId.Value : -1));
            if (!string.IsNullOrEmpty(_symbol))
                result = result.Where(p => p.Symbols.Contains(_symbol));
            result = result.OrderByDescending(x=>x.Date).Take(_count);
            return result;
		}
	}
}
